package com.zhengshang.api.controller.goodsshop;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.zhengshang.api.domain.AppBillProduct;
import com.zhengshang.api.domain.AppBillRecord;
import com.zhengshang.api.domain.AppPayRecord;
import com.zhengshang.api.service.IAppBillProductService;
import com.zhengshang.api.service.IAppBillRecordService;
import com.zhengshang.api.service.IAppPayRecordService;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.common.utils.ip.IpUtils;
import com.zhengshang.system.service.ISysUserService;
import com.zhengshang.third.wikeyun.WikeyunApi;
import com.zhengshang.third.wikeyun.WikeyunCallBack;
import com.zhengshang.third.wikeyun.WikeyunUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.TreeMap;

/**
 * 首页Controller
 *
 * @author zhengshang
 * @date 2021-03-09
 */
@Api(tags = "首页")
@RestController
@RequestMapping("/wikeyun")
public class WikeyunController extends BaseController {

    @Autowired
    private WikeyunUtils wikeyunUtils;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IAppPayRecordService appPayRecordService;
    @Autowired
    private IAppBillProductService appBillProductService;
    @Autowired
    private IAppBillRecordService appBillRecordService;


    /**
     * 获取卡券特权数据（直充、卡券）
     */
    @ApiOperation(value = "获取卡券特权数据（直充、卡券）")
    @GetMapping("/quanyiPrivilege")
    public AjaxResult quanyiPrivilege(HttpServletRequest request) {
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        params.put("id", "");
        params.put("pro_type", "1");
        params.put("store_id", wikeyunUtils.storeId);
        params.put("ip", IpUtils.getIpAddr(request));
        String result = wikeyunUtils.sendGetRequest(params, WikeyunApi.QuanyiPrivilege);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }

    /**
     * 获取卡券、直充初始化信息
     */
    @ApiOperation(value = "获取卡券、直充初始化信息")
    @GetMapping("/getThirdProInfo")
    public AjaxResult getThirdProInfo(HttpServletRequest request, Long id) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("id", id);
        params.put("ip", IpUtils.getIpAddr(request));
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.getThirdProInfo);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }

    /**
     * 推广酒店业务分销取链
     */
    @ApiOperation(value = "推广酒店业务分销取链")
    @GetMapping("/meituanGetLink")
    public AjaxResult meituanGetLink() {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("store_id", wikeyunUtils.storeId);
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.meituanGetLink);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }

    /**
     * 查询权益订单详情
     */
    @ApiOperation(value = "查询权益订单详情")
    @GetMapping("/queryQuanYiOrder")
    public AjaxResult queryQuanYiOrder(String orderNo) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("store_id", wikeyunUtils.storeId);
        params.put("order_no", orderNo);
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.quanyiOrderDetail);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }


    /**
     * 微客云集订单回调
     */
    @PostMapping(value = "/notify/wiKeYunServerOrder")
    public AjaxResult notifyWiKeYunServerOrder(@RequestBody WikeyunCallBack wikeyunCallBack) {
        System.out.println("进入微客云集回调/notify/wiKeYunServerOrder");
        String cms_order_num = wikeyunCallBack.getCms_order_num();
        String order_no = wikeyunCallBack.getOrder_no();
        String status = wikeyunCallBack.getStatus();
        String sign = wikeyunCallBack.getSign();
        logger.info("微客云集订单回调--------------start");
        logger.info("微客云集订单回调order_no：{}", order_no);
        logger.info("微客云集订单回调cms_order_num：{}", cms_order_num);
        logger.info("微客云集订单回调sign：{}", sign);
        logger.info("微客云集订单回调--------------end");
        String quanYiOrderSign = wikeyunUtils.getQuanYiOrderSign(order_no);
        if (quanYiOrderSign.equals(sign)) {
            AppPayRecord appPayRecord = appPayRecordService.selectAppPayRecordByOrderNum(cms_order_num);
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByOrderNum(cms_order_num);
            //获取数据
            if ("1".equals(status)) {
                //修改充值状态
                appBillRecord.setOrderState("3");
                Integer productType = appPayRecord.getProductType();
                //调用订单详情接口查卡密

                TreeMap<String, Object> params = new TreeMap<>();
                params.put("store_id", wikeyunUtils.storeId);
                params.put("order_no", order_no);
                params.put("cms_order_num", cms_order_num);
                String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.quanyiOrderDetail);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.getString("code");
                //获取数据
                if ("0000".equals(code)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray goodsCardData = data.getJSONArray("goods_card_data");
                    if (StringUtils.isNotNull(goodsCardData)) {
                        if (goodsCardData.size() == 1) {
                            JSONObject jsonObject1 = goodsCardData.getJSONObject(0);
                            String cardPassword = jsonObject1.getString("card_password");
                            appBillRecord.setCardPassword(cardPassword);
                        }
                    }
                    System.out.println("进入微客云集回调充值成功");
                }

                appBillRecordService.updateAppBillRecord(appBillRecord);
                Long userId = appBillRecord.getUserId();
                SysUser sysUser = sysUserService.selectUserById(userId);
                SysUser upUser = sysUserService.selectUserById(sysUser.getUpUserId());//上级账户
                if (ObjectUtils.isNotEmpty(upUser)) {
                    String productTypeName = "【影视会员】";
                    if (productType.equals(11)) {
                        productTypeName = "【影视会员】";
                    }
                    if (productType.equals(12)) {
                        productTypeName = "【音乐会员】";
                    }
                    if (productType.equals(13)) {
                        productTypeName = "【在线教育】";
                    }
                    if (productType.equals(16)) {
                        productTypeName = "【交通出行】";
                    }
                    if (productType.equals(17)) {
                        productTypeName = "【美食饮品】";
                    }
                    if (productType.equals(18)) {
                        productTypeName = "【酒店旅游】";
                    }
                    BigDecimal amount = appPayRecord.getPayMoney().multiply(new BigDecimal("0.01"));
                    sysUserService.updateTwoUserBalance(sysUser, amount, productTypeName);
                }
            } else {
                //走退款逻辑
                appBillRecord.setOrderState("2");
                appBillRecordService.updateAppBillRecord(appBillRecord);
                appPayRecordService.refund(appPayRecord);
            }
        }
        return AjaxResult.success("获取成功", "");
    }

}
